//
//  OAuthViewController.swift
//  weibo22
//
//  Created by keshuaiguo on 16/1/17.
//  Copyright © 2016年 keshuaiguo. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {

    
    //属性的webView
    let webView = UIWebView()
    
    
    //MARK:关闭页面
    @objc private func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    //自动填充账号
    @objc private func defoultAccount() {
    
        let jsString = "document.getElementById('userId').value = '18678993330@163.com',document.getElementById('passwd').value = 'gs900224'"
    
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    
    }
    override func loadView() {
        
        

        //将根视图 替换为webView
        view = webView
        
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavBar()
        
        //加载授权页面
        loadOAuthPage()
    }
    
    //设置导航条
    private func setNavBar() {
        
        //文字渲染
        //设置单个
//        navigationController?.navigationBar.tintColor  = UIColor.orangeColor()
        //设置全局UINavigationBar的颜色
//        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        
        //设置左侧按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        //自动登录
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defoultAccount")
    }
    
    //MARK加载授权页面
    private func loadOAuthPage() {
    
        //1.获取url
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)!
        
        //获取request
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
        
    }
}
//类扩展
extension OAuthViewController:UIWebViewDelegate {


    func webViewDidStartLoad(webView: UIWebView) {
        
        //显示
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        //隐藏
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print(request.URL?.absoluteString)
        
        //截取url中的 code授权码
        guard let urlString = request.URL?.absoluteString else {
        
            return false
        
        }
        
        
        if urlString.containsString("code=") {
        
//            print(urlString)
            
            guard let query = request.URL?.query else {
            
                return false
            }
            let codeStr = "code="
            //将query 转换NSString
            
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            //            print(code)
            loadAccessToken(code)
            //不希望页面跳转
            return false
        }
        
        return true
    }
    
    private func loadAccessToken(code: String) {
        //请求token 和用户信息
        
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if !isSuccess {
            
                print("用户登录失败")
                //HUD 用户登录失败
                SVProgressHUD.showErrorWithStatus("网络君正在睡觉,请稍后再试")
                return
            
            }
            //登录成功
            SVProgressHUD.showSuccessWithStatus("登陆成功")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
}









